<template>
  <div>
    <van-search @input="inputsearch" shape="round" v-model.trim="value" placeholder="请输入搜索关键词" />

     <template v-if="value===''">
     <van-cell title="热门搜索" style="color:#ccc" />
       <van-tag  @click="hotsearch(obj.first)" v-for="(obj,index) in hot" :key="index" round type="primary"  size="large" color="red" text-color="#000" :plain="true">{{obj.first}}</van-tag>
     </template>
      <template v-else>
         <van-cell title="最佳匹配" style="color:#ccc" />
         <van-list
         :immediate-check="false"
         error-text="已经到底了"
         :error="iserror"
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="onLoad"
>
<music-item  :row="item" v-for="item in list" :key="item.id" />

</van-list>
      </template>

  </div>
</template>

<script>
import MusicItem from '@/components/MusicItem'
import { searchkeywords, hotsearch } from '@/api/search'
export default {
  components: {
    MusicItem
  },
  data () {
    return {
      value: '',
      list: [],
      loading: false,
      finished: false,
      limit: 20,
      page: 1,
      iserror: false,
      count: 0,
      hot: []
    }
  },

  created () {
    this.gethotsongs()
  },

  methods: {
    hotsearch (val) {
      this.value = val
      this.loading = true
      this.loading = []
      this.onLoad()
    },
    inputsearch () {
      this.list = []
      this.page = 1
      this.loading = true
      clearTimeout(this.id)
      if (this.value === '') return
      this.id = setTimeout(() => {
        this.onLoad()
      }, 700)
    },
    async onLoad () {
      try {
        const res = await searchkeywords({
          keywords: this.value,
          limit: this.limit,
          offset: (this.page - 1) * this.limit
        })
        if (res.data.result.songs) {
          this.count = res.data.result.songCount
          this.list.push(...res.data.result.songs)
        } else {
          this.count = 0
        }
      } catch (error) {
        this.iserror = true
      }

      if (this.list.length >= this.count) {
        this.finished = true
      } else {
        this.loading = false
        this.page++
      }
    },
    async gethotsongs () {
      const res = await hotsearch()
      console.log(res)
      this.hot = res.data.result.hots
    }

  }
}

</script>

<style scoped lang='less'>
.contain {
  padding: 0 10px;
}
.van-tag {
  margin: 0 15px;
}
</style>
